package com.atguigu.InternetCoding;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 构造UDP接口函数
 *  1.public DatagramSocket(int port)，IP地址由系统分配，创建服务器端的UDP
 *  2.public DatagramSocket(int port， IntAddress laddr)，IP地址由系统分配,指定地址
 *  3.clost()关闭套接字
 *  4.public send(DatagramPacket p)从此套接字发送数据报包
 *  5.public receive(DatagramPacket p)接收数据报包
 *  6.InetAddress getLocalaDDress(),获取套接字绑定的本地地址
 *  7.public int getLocalPort()，返回套接字绑定的本地主机的端口号
 *  8.public InetAress getInetAddress()
 *  9.public int getPort(),如果套接字未连接返回-1
 *
 * DatagramPacket类
 *  1.public DatagramPacket(byte[] buf, int length)构造DatagramPacket,接收长length的数据包， length <= buf.length
 *  2.public DatagramPacket(byte[] buf, int length, InetAddress address, int port),指定主机，指定端口
 *  3.public InetAddress getAddress()返回某台机器的IP地址
 *  3.public int getPort()返回某台机器的端口
 *  4.public byte[] getData()返回数据缓冲区，offset含
 *  5.public int getLength()
 * @author xiaoqi
 * @data 2021/04/27 11:26
 */
public class UDPServer {
    public static void main(String[] args) throws IOException {
        //建立UDP接口
        DatagramSocket socket = new DatagramSocket(9999);
        byte[] by = new byte[1024];
        //建立接收信息包
        DatagramPacket datagramPacket = new DatagramPacket(by,0,by.length);
        //接收信息
        socket.receive(datagramPacket);
        //打印信息
        System.out.println(new String(datagramPacket.getData()));
        //关闭信息
        socket.close();
    }

}
